#!/usr/bin/env bash

# Requirements:
# grep, curl, git

DEFAULT_VER=v0.39.7

SHELL_RC=$HOME/.$(basename $SHELL)rc
NODE_MIRROR=https://npmmirror.com/mirrors/node/

export NVM_DIR="$HOME/.nvm"

function check () {
  [[ -d $NVM_DIR ]] && echo "$NVM_DIR" already exist! && return 1
  
  export GITBIN=`which git 2>/dev/null`
  [[ -z $GITBIN ]] && echo git is required! && return 2
  
  export GREP=`which grep 2>/dev/null`
  [[ -z $GREP ]] && echo grep is required! && return 2

  return 0
}

function install () {
  # fetch latest tag to use
  export NVM_VER=`curl -s https://gitee.com/api/v5/repos/mirrors/nvm/tags\?sort\=updated\&direction\=desc |\
  grep -Eo '\[{"name":"v([.0-9]+)"' | grep -Eo 'v[.0-9]+'`
  
  [[ -z $NVM_VER ]] && NVM_VER=$DEFAULT_VER
  echo Using nvm version: $NVM_VER

  # install via git, shallow clone
  git clone -b $NVM_VER --depth 1 https://gitee.com/mirrors/nvm.git ${NVM_DIR}

  return $?
}

function setup () {
  # setup .rc
  grep -q NVM_DIR $SHELL_RC || cat >> $SHELL_RC <<EOF

export NVM_NODEJS_ORG_MIRROR=$NODE_MIRROR
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"
[ -s "$NVM_DIR/bash_completion" ] && . "$NVM_DIR/bash_completion"
EOF
  
  # setup calling shell
  export NVM_NODEJS_ORG_MIRROR=$NODE_MIRROR
  export NVM_DIR
  source $NVM_DIR/nvm.sh
  source $NVM_DIR/bash_completion
  
  echo 'NODE_MIRROR' $NODE_MIRROR
  echo
  echo Done! Try \"nvm ls-remote --lts\" or \"nvm install lts/fermium\"
  echo
}

check && install && setup